package com.umeox.watch.moto.launcher.fragment;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.umeox.moto.watch.themes.app.ThemeFragment;
import com.umeox.moto.watch.themes.app.ThemeManager;
import com.umeox.moto.watch.themes.widget.RoundProgressBar;
import com.umeox.moto.watch.themes.widget.TextView;
import com.umeox.watch.moto.apiclient.model.FriendStepDTO;
import com.umeox.watch.moto.apiclient.model.StepRankingDTO;
import com.umeox.watch.moto.dataservice.DataProvider;
import com.umeox.watch.moto.launcher.R;
import com.umeox.watch.moto.launcher.adapter.ChallengeStepRankingAdapter;
import com.umeox.watch.moto.pedometer.util.StepManager;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class ChallengeStepsFragment extends ThemeFragment {

    private static final String TAG = "ChallengeStepsFragment";

    private ChallengeStepRankingAdapter mStepRankingAdapter;

    private Handler handler;

    private final Runnable getStepRankingRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                StepRankingDTO stepRanking = StepManager.getInstance().getStepRanking();
                if (stepRanking == null) {
                    return;
                }
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void run() {
                        //更新ui
                        //刷新列表
                        mStepRankingAdapter.setFriendStepOTDList(fixFriendStepOTDList(stepRanking));
                        //刷新当前步数
                        tvNumber.setText("" + stepRanking.step);
                        //刷新排名文本
                        if (stepRanking.step == 0) {
                            tvRankingTip.setVisibility(View.GONE);
                        } else {
                            tvRankingTip.setVisibility(View.VISIBLE);
                            tvRankingTip.setText(getString(R.string.step_ranking_tip, stepRanking.surpassScale));
                        }
                        //刷新进度条
                        stepPb.setProgress(stepRanking.step, stepRanking.stepPlan);
                        //刷新奖杯颜色
                        if (stepRanking.step < stepRanking.stepPlan) {
                            //未完成
                            ivStepCup.setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.ic_steps_grey));
                        } else {
                            //已完成
                            ivStepCup.setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.ic_steps_highlight));
                        }
                    }
                });
            } catch (RemoteException e) {
                Log.e(TAG, "getStepRankingData Error", e);
            }
        }
    };
    private TextView tvNumber;
    private TextView tvRankingTip;
    private RoundProgressBar stepPb;
    private ImageView ivStepCup;

    @SuppressLint("NewApi")
    private List<FriendStepDTO> fixFriendStepOTDList(StepRankingDTO stepRanking) {
        //新建列表
        ArrayList<FriendStepDTO> tempArray = new ArrayList<>(stepRanking.friendsStep);
        //添加自己的数据
        FriendStepDTO selfStepDTO = new FriendStepDTO();
        selfStepDTO.memberId = DataProvider.getHolderId();
        selfStepDTO.type = -1;
        selfStepDTO.name = DataProvider.getNickname();
        selfStepDTO.avatar = DataProvider.getAvatar();
        selfStepDTO.avatarIndex = -1;
        selfStepDTO.createTime = System.currentTimeMillis();
        selfStepDTO.amount = stepRanking.step;
        tempArray.add(selfStepDTO);
        // 先进行排序，按amount降序，如果amount相等则自己的数据排在前面
        final String selfMemberId = DataProvider.getHolderId();
        tempArray.sort(new Comparator<FriendStepDTO>() {
            @Override
            public int compare(FriendStepDTO o1, FriendStepDTO o2) {
                if (o2.amount == o1.amount && o1.memberId.equals(selfMemberId)) {
                    return -1;
                }
                if (o2.amount == o1.amount && o2.memberId.equals(selfMemberId)) {
                    return 1;
                }
                return o2.amount - o1.amount;
            }
        });

        return tempArray;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.frag_step;
    }

    @Override
    protected void initView(View rootView) {
        tvNumber = rootView.findViewById(R.id.tvNumber);
        tvRankingTip = rootView.findViewById(R.id.tvRankingTip);
        stepPb = rootView.findViewById(R.id.stepPb);
        ivStepCup = rootView.findViewById(R.id.ivStepCup);
        RecyclerView mStepRv = rootView.findViewById(R.id.rv_step);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mStepRv.setLayoutManager(linearLayoutManager);
        mStepRv.setHasFixedSize(true);
        mStepRankingAdapter = new ChallengeStepRankingAdapter(mContext);
        mStepRv.setAdapter(mStepRankingAdapter);

        HandlerThread handlerThread = new HandlerThread("StepRankingData_thread");
        handlerThread.start();
        handler = new Handler(handlerThread.getLooper());

        if (ThemeManager.getInstance().getCurrentTheme() == 0) {
            //暗色
            stepPb.setProgressBgColor(Color.parseColor("#4C545C"));
        } else {
            //亮色
            stepPb.setProgressBgColor(Color.parseColor("#D4D6D5"));
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        handler.post(getStepRankingRunnable);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(getStepRankingRunnable);
    }
}
